package com.anuo.app.study.studydesignpatterns;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:spring/spring-context.xml"})

public class StudySingleton {

    @Test
    public void studySingleton(){
        StudySingleton studySingleton=StudySingleton.getInstance();
    }
    //常用(线程安全的)
    //参考: https://www.journaldev.com/171/thread-safety-in-java-singleton-classes-with-example-code
    private static StudySingleton instance;
    private static Object object=new Object();
    public static StudySingleton getInstance() {

        //To avoid this extra overhead every time, double checked locking principle is used.
        //(这样不至于每次获取实例都去锁对象, 浪费系统资源)
        if (instance == null) {
            synchronized (object) {
                if (instance == null) {
                    instance = new StudySingleton();
                }
            }
        }
        return instance;
    }
    //常用(线程不安全)
//    private static StudySingleton instance;
//
//    public static StudySingleton getInstance() {
//        if (instance == null) {
//            instance = new StudySingleton();
//        }
//        return instance;
//    }

    //最简洁的写法和最有效的写法
//    public enum Foo {
//        INSTANCE;
//    }
//  参考: https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java

    //其他写法见 http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
}
